<?php
namespace app\admin\controller;

use app\common\crypt\Crypt;
use app\common\helper\Tree;
use think\Config;
use think\Controller;
use app\model\User as UserModel;
use app\admin\validate\login\Login as LoginValidate;
use think\Db;
use think\Session;

class Login extends Controller
{
    /**
     * 后台登录
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $session = new Session();
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new LoginValidate();
            if (!$validate->check($data)) {
                $this->doRedirect($validate->getError(), "2");
            }
            $user = Db::table('aya_user')->where('user_account', '=', $data['user_account'])
                ->where('user_status', '<>', -1)->find();
            if (empty($user)) {
                $this->doRedirect('该用户不存在', "2");
            }
            if ($user['user_status'] == 0) {
                $this->doRedirect('该用户已被禁用', "2");
            }
            $crypt = new Crypt();
            $password = $crypt::decrypt($user['password']);
            if ($password != $data['password']) {
                $this->doRedirect('密码不正确', "2");
            }
            $roleId = $user['roleId'];
            $role = Db::table('aya_role')->where('id', '=', $roleId)
                ->where('status', '<>', -1)->find();
            $menuArr = []; // 获取用户权限数组
            $urlArr = []; // 获取用户权限跳转路径数组
            if ($user['user_id'] == 1) { //如果为超级管理员
                $menuArr = Db::table('aya_menu')->where('menu_status', '=', 1)
                    ->where('menu_is_admin', '=', 1)
                    ->order('menu_sort', 'asc')
                    ->select();
                $urlArr = Db::table('aya_menu')->where('menu_status', '=', 1)
                    ->where('menu_is_admin', '=', 1)
                    ->field('menu_page_url')
                    ->select();
            } else {
                // 如果设置了角色
                if (!empty($role)) {
                    $rules = $role['role_menu'];
                    $rulesArr = explode(',', $rules);
                    if (!empty($rulesArr)) {
                        $menuArr = Db::table('aya_menu')->where('menu_status', '=', 1)
                            ->where('menu_is_admin', '=', 1)
                            ->where('menu_id', 'in', $rules)
                            ->order('menu_sort', 'asc')->select();
                        $urlArr = Db::table('aya_menu')
                            ->where('menu_is_admin', '=', 1)
                            ->where('menu_status', '=', 1)
                            ->where('menu_id', 'in', $rules)
                            ->field('menu_page_url')->select();
                    }
                }
            }
            $urlValueArr = array();
            if (!empty($urlArr)) {
                foreach ($urlArr as $url) {
                    array_push($urlValueArr, $url['menu_page_url']);
                }
            }
            $leftMenuTree = Tree::makeTree($menuArr);
            $session->set('urlArr', $urlValueArr);
            $session->set('leftMenuTree', $leftMenuTree);
            session('currentUser', $user);
            $config = new Config();
            $expireTime = empty($config->get('expire_time')) ? 3600 : $config->get('expire_time');
            session('expire_time', time() + $expireTime);
            $model = new UserModel();
            $model->save(['login_ip' => $this->request->ip()], ['id' => $user['id']]);
            $this->doRedirect('登录成功', "1", "index/index");
        }
        if ($session->has('expire_time') && $session->get('expire_time') > time() && $session->has('currentUser') && !empty(session('currentUser'))) {
            $this->redirect('index/index');
        }
        return $this->fetch('index');
    }

    /**
     * 后台验证后返回信息
     * @param string $msg
     * @param string $icon
     * @param null $url
     * @param string $data
     */
    protected function doRedirect($msg = '', $icon = '2', $url = null, $data = '')
    {
        if ($url == null) {
            $url = $this->request->server('HTTP_REFERER');
        }

        if ($msg == '') {
            $msg = '操作失败！';
        }
        $this->redirect($url, $data, 302, ['error_message' => $msg . '|' . $icon, 'form_info' => $this->param]);
    }
}